<template>
	<div :class="curClassName" :style="curStyle" @click="handleClick">
		<img :src="imgUrl" />
	</div>
</template>
<script setup lang="ts">
import { ImgurlBase64 } from '@/core/utils/imgurl-base64';
import { IEvent, calcFilemime } from '@/core';
import {
	getDownloadUrl,
} from '@/hooks/use-editor';
import { Http } from '@/http/http';
import { FieldImageDynamicProps } from './field-image-dynamic';
const props = defineProps(FieldImageDynamicProps);
interface RawItemImageEmit {
	(name: 'component-action', value: IEvent<string>): void;
}
const emit = defineEmits<RawItemImageEmit>();
/**
 * 项名称
 *
 * @memberof FieldImageDynamic
 */
const itemName = computed(() => {
	return props.index || props.index === 0
		? `${props.name}_${props.index}`
		: props.name;
});

/**
 * 当前容器样式
 *
 * @memberof FieldImageDynamic
 */
const curStyle = computed(() => {
	const layoutModel = props.layoutModelDetails[itemName.value];
	if (layoutModel) {
		return layoutModel.getElementStyle();
	}
});

/**
 * 类名
 *
 * @memberof FieldImageDynamic
 */
const curClassName = computed(() => {
	const layoutModel = props.layoutModelDetails[itemName.value];
	const classNames = {
		'app-field-image-dynamic': true
	};
	if (layoutModel) {
		Object.assign(classNames, layoutModel.getClassNames());
	}
	return classNames;
});

/**
 * 动态图片路径
 *
 * @memberof AppFieldImageDynamic
 */
const dynaImgUrl = ref('');


/**
 * 处理文件加载
 * 
 * @memberof AppFieldImageDynamic
 */
 const handleFileLoad = async (file: any) => {
	const fileValue: any = file
	const tempUrl = getDownloadUrl();
	let url = `${tempUrl}/${fileValue.id}`;
	fileValue.url = url;
	console.log('export_params',url == fileValue.url);
	
	const tempFile = await getFile(fileValue);
	dynaImgUrl.value = tempFile.url;
}

/**
 * 获取文件
 * 
 * @memberof AppFieldImageDynamic
 */
const getFile = async (file: any): Promise<any> => {
	const tempFile = JSON.parse(JSON.stringify(file));
	try {
		const response = await Http.getHttp()({
			method: 'get',
			url: tempFile.url,
			responseType: 'blob',
		});
		if (
			!response ||
			(response.hasOwnProperty('status') && response.status != 200) ||
			(response.hasOwnProperty('success') && (response as any).success == false)
		) {
			App.getNotificationHelper().warning(
				App.ts('common.fileupload.loadfail', '加载失败')
			);
			return;
		}
		// 请求成功，后台返回的是一个文件流
		if (response.data) {
			// 获取文件名
			const filename = tempFile.name;
			const ext = '.' + filename.split('.').pop();
			let filetype = calcFilemime(ext);
			// 用blob对象获取文件流
			let blob = new Blob([response.data], { type: filetype });
			tempFile.isImage = isImage(filetype);
			if (tempFile.isImage) {
				let fileReader = new FileReader();
				return new Promise((resolve: any, reject: any) => {
					fileReader.onload = (e: any) => {
						tempFile.url = e.target.result;
						resolve(true);
					};
					fileReader.readAsDataURL(blob);
				}).then((response: any) => {
					return tempFile;
				});
			} else {
				return tempFile;
			}
		} else {
			console.error(response);
		}
	} catch (error) {
		console.error(error);
	}
};


/**
 * 判断是否为图片文件
 * 
 * @memberof AppFieldImageDynamic
 */
const isImage = (filetype: string) => {
	const imageTypes = ['image/jpeg', 'image/gif', 'image/png', 'image/bmp'];
	if (imageTypes.indexOf(filetype) > -1) {
		return true;
	} else {
		return false;
	}
};

/**
 * 处理动态图片
 *
 * @memberof AppFieldImageDynamic
 */
const handleDynaImg = async () => {
	const downloadUrl = App.getProjectSetting().exportFileUrl;
	if (props.value && typeof props.value == 'string') {
		// 默认识别文件对象形式，识别失败则为全路径模式
		try {
			const _files = JSON.parse(props.value);
			const file = _files instanceof Array ? _files[0] : null;
			const url = `${downloadUrl}/${file.id}`
			const res: any = await ImgurlBase64.getInstance().getImgURLOfBase64(url);
			if (res !== '/'){				
				dynaImgUrl.value = res;
			}else {
				handleFileLoad(file);
			}
		} catch (error) {
			dynaImgUrl.value = props.value;
		}
	}
};


watch(
	() => props.value,
	() => {
		handleDynaImg();
	}
);

onMounted(() => {
	handleDynaImg();
});

/**
 * 图片路径
 * 
 * @memberof AppFieldImageDynamic
 */
const imgUrl = computed(() => {
	return dynaImgUrl.value;
});

/**
 * 处理点击
 * @param $event 
 * @memberof AppFieldImageDynamic
 */
 const handleClick = ($event:any) => {
	emit('component-action', {
		name: props.name,
		action: 'panelItemClick',
		data: $event,
	});
};
</script>
